<template>
  <div class="chart-container">
    <h1 v-if="showInput">TestAgent TimeLine</h1>
    <div class="input-container" v-if="showInput">
      <input v-model="processId" placeholder="输入process ID" @keyup.enter="loadProcessData" class="process-input" />
      <button @click="loadProcessData" class="load-button">加载数据</button>
    </div>
    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="chartOptions" class="chart-wrapper">
      <el-button 
        type="primary" 
        @click="showChart = !showChart"
        style="margin-bottom: 16px;"
      >
        {{ showChart ? 'Hide Chart' : 'Show Chart' }}
      </el-button>

      <div v-if="showChart">
        <apexchart type="rangeBar" height="1800" width="100%" :options="chartOptions" :series="seriesComputed">
        </apexchart>
      </div>

      <LargeActivityTable
        :table-data="largeActivityData"
      />

      <ProcessRankChart
        v-if="rankSeries"
        :series="rankSeries"
        @data-point-selection="handleDataPointSelection"
      />

      <TestCaseTable
        v-if="tableData.length"
        :table-data="tableData"
        @details="handleDetails"
      />

   
    </div>
  </div>

  <TestDetailsDialog ref="detailsDialog" />
</template>

<script setup>
import { ref, computed,  onBeforeMount } from 'vue';
import { ElButton } from 'element-plus';
import { fetchProcessData, fetchTestRunnerData, fetchLargeAutoTestActivity} from '../services/esService';
import { groupBy } from '../utils/arrayHelper';
import { calculateDurationInMinutes, formatDate } from '../utils/dateUtils';
import ProcessRankChart from './charts/ProcessRankChart.vue';
import TestCaseTable from './tables/TestCaseTable.vue';
import LargeActivityTable from './tables/LargeActivityTable.vue';
import TestDetailsDialog from './modals/TestDetailsDialog.vue';

const processId = ref('');
const error = ref('');
const chartOptions = ref({
      plotOptions: {
        bar: {
          horizontal: true,
          barHeight: '50%',
          rangeBarGroupRows: true
        }
      },
      fill: { type: "solid" },
      yaxis: {
        show: true,
      },
      xaxis: {
        type: 'datetime',
        labels: {
          datetimeUTC: false
        }
      },
      tooltip: {
        x: {
          show: false,
          format: 'HH:mm',
        }
      },
      legend: { show: false }
    });
const showInput = ref(true);    
const chartSeries = ref([]);    
const rankSeries = ref(null);
const showChart = ref(false);
const tableData = ref([]);
const largeActivityData = ref([]);
const detailsDialog = ref(null);

let groupData = undefined;

const seriesComputed = computed(() => {
  if (!chartSeries.value) return [];
  return JSON.parse(JSON.stringify(chartSeries.value));
});

const loadProcessData = async () => {
  if (!processId.value) {
    error.value = '请输入Process ID';
    return;
  }

  try {
    const data = await fetchProcessData(processId.value);
    error.value = '';
    groupData = groupBy(data, "testRunner");
    const minStartTime = new Date(Math.min(...data.map(item => new Date(item.startTime))));
    const maxEndTime = new Date(Math.max(...data.map(item => new Date(item.endTime))));
    const largeData = await fetchLargeAutoTestActivity(minStartTime, maxEndTime);
    largeActivityData.value = largeData;

    const tempSeriesData = [];
    for (const key in groupData) {
      const tempSeries = {
        name: key,
        data: [],
      };
      groupData[key].forEach((item) => {
        const startTime = new Date(item.startTime);
        const endTime = new Date(item.endTime);
        tempSeries.data.push({
          x: item.agentName,
          y: [startTime.getTime(), endTime.getTime()],
        });
      });
      tempSeriesData.push(tempSeries);
    }
    chartSeries.value = tempSeriesData;
    const sortedData = data.map(item => {
      const startTime = new Date(item.startTime);
      const endTime = new Date(item.endTime);
      const durationInMinutes = calculateDurationInMinutes(startTime, endTime);
      return {
        ...item,
        duration: durationInMinutes
      };
    }).sort((a, b) => b.duration - a.duration)
      .slice(0, 20).map(it => ({
        x: it.testRunner,
        y: it.duration
      }));
    rankSeries.value = [
      {
        name: '耗时（分钟）',
        data: sortedData
      }
    ];
  } catch (err) {
    error.value = err.message;
  }
};

const initializeProcessId = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const queryProcessId = urlParams.get('processId');
  if (queryProcessId) {
    showInput.value = false;
    processId.value = queryProcessId;
    loadProcessData();
  }
};

onBeforeMount(() => {
  initializeProcessId();
});

const handleDataPointSelection = async ({ event, chartContext, config }) => {
  const testRunner = config.w.config.series[config.seriesIndex].data[config.dataPointIndex].x;
  const data = await fetchTestRunnerData(processId.value, groupData[testRunner][0]);
  tableData.value = data.map(testCase => ({
    testCase: testCase.TestCase,
    StartCaseTime: formatDate(new Date(testCase.StartCaseTime)),
    Success: testCase.Success,
    AgentName: testCase.host.name,
    durationInMinutes: calculateDurationInMinutes(testCase.StartCaseTime, testCase.EndCaseTime),
    EndCaseTime: formatDate(new Date(testCase.EndCaseTime)),
  }));
};

const handleDetails = (row) => {
  detailsDialog.value?.show(row);
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  padding: 20px;
}

.input-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.process-input {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  flex-grow: 1;
}

.load-button {
  padding: 8px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.load-button:hover {
  background-color: #66b1ff;
}

.error-message {
  color: red;
  margin-bottom: 10px;
}

.chart-wrapper {
  margin-top: 20px;
}
</style>
